﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Diagnostics;

namespace Hallenberg.Core.IO
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "CSV"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
    public class CSVFileRow : Collection<string>
    {
        private ReadOnlyCollection<string> m_Header;

        internal static CSVFileRow Parse(string line, char[] separators, ReadOnlyCollection<string> header)
        {
            Debug.Assert(!string.IsNullOrEmpty(line));
            if (string.IsNullOrEmpty(line))
            {
                throw new ArgumentNullException("line");
            }

            CSVFileRow row = new CSVFileRow()
            {
                m_Header = header
            };

            foreach (string column in line.Split(separators, StringSplitOptions.RemoveEmptyEntries))
            {
                string cleanedColumn = column;

                if (cleanedColumn.StartsWith("\"", StringComparison.OrdinalIgnoreCase))
                {
                    cleanedColumn = cleanedColumn.Remove(0, 1);
                    if (cleanedColumn.EndsWith("\"", StringComparison.OrdinalIgnoreCase))
                    {
                        cleanedColumn = cleanedColumn.Remove(cleanedColumn.Length - 1, 1);
                    }
                }

                row.Add(cleanedColumn);
            }

            return row;
        }

        public string this[string index]
        {
            get
            {
                int columnIndex = m_Header.IndexOf(index);
                if (columnIndex == -1)
                {
                    throw new ArgumentOutOfRangeException("index", "Unknown column name");
                }

                return this[columnIndex];
            }
        }
    }
}
